// pages/visa/visa.js

const app = getApp();

Page({
  data: {
    // 热门国家数据
    countries: [],
    showModal: false,

    // 服务项目数据
    services: [
      { icon: '/pages/images/icons/check 1.png', name: '拒签退款' },
      { icon: '/pages/images/icons/target 1.png', name: '全程追踪' },
      { icon: '/pages/images/icons/face 1.png', name: '智能证件照' },
      { icon: '/pages/images/icons/qq.png', name: '极速出签' },
      { icon: '/pages/images/icons/q.png', name: '智能申请表' },
      { icon: '/pages/images/icons/truck 1.png', name: '顺丰派送' }
    ],
    searchValue: '', // 搜索框的值
    statusBarHeight: 0, // 状态栏高度

    //轮播图
     imgUrls: [
      'https://visa.goldenholiday.com/images/country/poster.jpg',
      'https://visa.goldenholiday.com/images/country/poster1.png',
      'https://visa.goldenholiday.com/images/country/poster2.jpg'
    ],
    indicatorDots: true,  // 是否显示面板指示点
    autoplay: true,      // 是否自动切换
    interval: 5000,     // 自动切换时间间隔
    duration: 1000,     // 滑动动画时长
    swiperHeight: 210

  },
  // 添加检查登录状态的方法
  checkAuthStatus() {
    try {
      const userInfoStr = wx.getStorageSync('userInfo');
      
      // 如果 userInfoStr 为空，直接处理未登录状态
      if (!userInfoStr) {
        wx.showModal({
          title: '提示',
          content: '请先登录后再操作',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me'
              });
            }
          }
        });
        return false;
      }
  
      // 安全地解析 JSON
      let userInfo;
      try {
        userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr;
      } catch (e) {
        console.error('解析用户信息失败：', e);
        // 清除可能损坏的数据
        wx.removeStorageSync('userInfo');
        wx.showModal({
          title: '提示',
          content: '登录信息已失效，请重新登录',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me'
              });
            }
          }
        });
        return false;
      }
      
      if (!userInfo || !userInfo.phone) {
        wx.showModal({
          title: '提示',
          content: '请先绑定手机号后再操作',
          confirmText: '去绑定',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me'
              });
            }
          }
        });
        return false;
      }
      
      return true;
    } catch (error) {
      console.error('验证用户状态时发生错误：', error);
      wx.showToast({
        title: '系统错误，请稍后重试',
        icon: 'none'
      });
      return false;
    }
  },

  // 修改导航方法
  navigateToDetail(e) {
    if (!this.checkAuthStatus()) {
      return;
    }
    
    const itemId = e.currentTarget.dataset.id;
    const itemImage = e.currentTarget.dataset.image;
    wx.navigateTo({
      url: `/pages/countryitem/countryitem?id=${itemId}&image=${encodeURIComponent(itemImage)}`,
    });
  },

  // 修改搜索确认事件
  onSearchInput(e) {
    if (!this.checkAuthStatus()) {
      return;
    }

    const searchQuery = e.detail.value;
    if (searchQuery && searchQuery.trim()) {
      wx.setStorageSync('searchQuery', searchQuery);
      wx.switchTab({
        url: '/pages/country/country',
        success: () => {
          console.log('跳转成功，搜索值：', wx.getStorageSync('searchQuery'));
        },
        fail: (error) => {
          console.error('跳转失败：', error);
          wx.removeStorageSync('searchQuery');
        }
      });
    }
  },
  // 搜索框清除按钮
  onSearchClear() {
    this.setData({
      searchValue: ''
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  // 抽取国家数据请求逻辑
  fetchCountries(callback) {
    wx.request({
      url: 'https://visa.goldenholiday.com/api/miniapp/admin/country/public/list',
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 1) {
          const enabledCountries = res.data.data.filter(item => item.status === 1);
          const pricePromises = enabledCountries.map(country => {
            return new Promise((resolve) => {
              wx.request({
                url: `https://visa.goldenholiday.com/api/miniapp/admin/visaProduct/countryitemlist/${country.id}`,
                method: 'GET',
                header: {
                  'content-type': 'application/json'
                },
                success: (priceRes) => {
                  if (priceRes.data.code === 1 && priceRes.data.data.length > 0) {
                    const prices = priceRes.data.data.map(item => item.price);
                    const minPrice = Math.min(...prices);
                    resolve({ ...country, price: minPrice });
                  } else {
                    resolve({ ...country, price: country.price });
                  }
                },
                fail: () => {
                  resolve({ ...country, price: country.price });
                }
              });
            });
          });
          Promise.all(pricePromises).then(countriesData => {
            const formattedData = countriesData.map(item => ({
              name: item.name,
              name1: item.name1,
              price: item.price,
              image: item.image,
              id: item.id
            }));
            this.setData({ countries: formattedData });
            if (typeof callback === 'function') callback();
          });
        } else {
          wx.showToast({ title: '获取数据失败', icon: 'none' });
          if (typeof callback === 'function') callback();
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
        console.error('请求失败：', err);
        if (typeof callback === 'function') callback();
      }
    });
  },

  // 页面加载时调用
  onLoad(options) {
    this.fetchCountries();
  },

  // 下拉刷新时调用
  onPullDownRefresh() {
    wx.showLoading({ title: '加载中...' });
    this.fetchCountries(() => {
      wx.stopPullDownRefresh(); // 停止下拉刷新动画
      wx.hideLoading();
    });
  },
  
  showActivityModal() {
    this.setData({
      showModal: true
    });
  },

  // 隐藏活动弹窗
  hideActivityModal() {
    this.setData({
      showModal: false
    });
  },
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})
